<template>
  <div class="app-container">
    <!-- 查询表单：固定meterId=501，仅保留日期筛选 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用水日期" prop="analyseDate">
        <el-date-picker
            clearable
            v-model="queryParams.analyseDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择用水日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 功能按钮：保留原有操作逻辑 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['water:meterAnalyse:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['water:meterAnalyse:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['water:meterAnalyse:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['water:meterAnalyse:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格：仅展示meterId=501的数据 -->
    <el-table
        v-loading="loading"
        :data="meterAnalyseList"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="顺序Id" align="center" prop="id" />
      <el-table-column label="水表Id" align="center" prop="meterId" /> <!-- 固定显示501 -->
      <el-table-column label="水表名" align="center" prop="meterName" />
      <el-table-column label="当日用量" align="center" prop="todayUsage" /> <!-- 核心字段 -->
      <el-table-column label="当天最小流量" align="center" prop="todayMinVal" /> <!-- 可选字段 -->
      <el-table-column label="用水日期" align="center" prop="analyseDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.analyseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
              link type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['water:meterAnalyse:edit']"
          >修改</el-button>
          <el-button
              link type="primary"
              icon="Delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['water:meterAnalyse:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页：复用原有逻辑 -->
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 弹窗：仅保留「日期、当日用量、最小用量（可选）」 -->
    <el-dialog :title="title" v-model="open" width="400px" append-to-body>
      <el-form ref="meterAnalyseRef" :model="form" :rules="rules" label-width="100px">
        <!-- 隐藏meterId：固定为501，无需用户输入 -->
        <el-form-item v-show="false" prop="meterId">
          <el-input v-model="form.meterId" />
        </el-form-item>
        <!-- 用水日期：必填 -->
        <el-form-item label="用水日期" prop="analyseDate">
          <el-date-picker
              v-model="form.analyseDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
              style="width: 100%"
          />
        </el-form-item>
        <!-- 当日用量：必填 -->
        <el-form-item label="当日用量" prop="todayUsage">
          <el-input
              v-model="form.todayUsage"
              type="number"
              placeholder="请输入当日用量"
              min="0"
          />
        </el-form-item>
        <!-- 最小用量：可选 -->
        <el-form-item label="最小用量" prop="todayMinVal">
          <el-input
              v-model="form.todayMinVal"
              type="number"
              placeholder="可选，输入最小用量"
              min="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Meter501Analyse">
import { listMeterAnalyse, getMeterAnalyse, delMeterAnalyse, addMeterAnalyse, updateMeterAnalyse } from "@/api/water/meterAnalyse"
const { proxy } = getCurrentInstance()

// 状态管理：复用原有结构，简化非必要字段
const meterAnalyseList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

// 核心数据：固定meterId=501，精简表单字段
const data = reactive({
  form: {
    id: null,
    meterId: 501, // 固定筛选501表
    analyseDate: null, // 手动输入日期
    todayUsage: null, // 手动输入当日用量
    todayMinVal: null // 手动输入最小用量（可选）
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    meterId: 501, // 查询时默认筛选501
    analyseDate: null // 仅保留日期筛选
  },
  rules: {
    // 验证规则：日期和当日用量必填，最小用量可选
    analyseDate: [
      { required: true, message: "请选择用水日期", trigger: "blur" }
    ],
    todayUsage: [
      { required: true, message: "请输入当日用量", trigger: "blur" },
      { type: "number", min: 0, message: "用量不能为负数", trigger: "blur" }
    ],
    todayMinVal: [
      { type: "number", min: 0, message: "最小用量不能为负数", trigger: "blur" } // 仅验证格式，不强制必填
    ],
    meterId: [
      { required: true, message: "水表ID不能为空", trigger: "blur" } // 隐藏字段，确保提交
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询501表数据：复用原有逻辑，自动带meterId=501 */
function getList() {
  loading.value = true
  listMeterAnalyse(queryParams.value).then(response => {
    meterAnalyseList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消弹窗：重置表单
function cancel() {
  open.value = false
  reset()
}

// 表单重置：保留meterId=501，清空其他输入
function reset() {
  form.value = {
    id: null,
    meterId: 501, // 重置后仍保持501
    analyseDate: null,
    todayUsage: null,
    todayMinVal: null
  }
  proxy?.resetForm("meterAnalyseRef")
}

/** 搜索：仅按日期筛选501表数据 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置搜索：清空日期，恢复默认查询 */
function resetQuery() {
  proxy?.resetForm("queryRef")
  queryParams.value.analyseDate = null // 重置日期筛选
  handleQuery()
}

// 表格多选：复用原有逻辑
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增：打开弹窗，标题为新增 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增501表用量数据"
}

/** 修改：获取原有数据，回显到弹窗 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getMeterAnalyse(_id).then(response => {
    // 仅回显需要的字段，确保meterId仍为501
    form.value = {
      id: response.data.id,
      meterId: 501,
      analyseDate: response.data.analyseDate,
      todayUsage: response.data.todayUsage,
      todayMinVal: response.data.todayMinVal
    }
    open.value = true
    title.value = "修改501表用量数据"
  })
}

/** 提交：新增/修改通用，验证后提交 */
function submitForm() {
  proxy?.$refs["meterAnalyseRef"].validate(valid => {
    if (valid) {
      const submitFn = form.value.id ? updateMeterAnalyse : addMeterAnalyse
      submitFn(form.value).then(() => {
        proxy?.$modal.msgSuccess(form.value.id ? "修改成功" : "新增成功")
        open.value = false
        getList() // 提交后刷新列表
      })
    }
  })
}

/** 删除：复用原有逻辑，仅删除501表数据 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy?.$modal.confirm(`是否确认删除501表数据编号为"${_ids}"的记录？`).then(() => {
    return delMeterAnalyse(_ids)
  }).then(() => {
    getList()
    proxy?.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出：仅导出501表数据 */
function handleExport() {
  proxy?.download('water/meterAnalyse/export', {
    ...queryParams.value
  }, `meter501_analyse_${new Date().getTime()}.xlsx`)
}

// 页面加载时自动查询501表数据
getList()
</script>